package com.example.werewolf.service.impl.role;

import com.alibaba.fastjson2.JSONObject;
import com.example.werewolf.common.ActionType;
import com.example.werewolf.common.Camp;
import com.example.werewolf.entity.Event;
import com.example.werewolf.entity.GamePhase;
import com.example.werewolf.entity.Player;
import com.example.werewolf.model.ActionSkill;
import com.example.werewolf.model.GameChatResp;
import com.example.werewolf.service.ActionStrategy;
import com.example.werewolf.utils.PrintUtils;
import com.example.werewolf.utils.RoleUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Component
public class ProphetActionStrategy implements ActionStrategy {

    @Override
    public ActionSkill execute(List<Player> players, List<Player> actionPlayers,
                               GamePhase phase, List<Event> publicEvents, SseEmitter emitter) throws IOException {
        if (actionPlayers.isEmpty()) return null;

        Player prophet = actionPlayers.get(0);
        System.out.println("🔮 预言家行动：请选择查验一名玩家（输出编号）");

        // 查验的前提是玩家还存活
        String events = "你所了解的信息：" + publicEvents + "，和" + prophet.getEvents();
        String chat = prophet.chat(events + "预言家行动：请选择你想要查验一名玩家（输出编号），并给出你的思考过程");
        GameChatResp resp = parseResponse(chat);

        Integer target = resp != null ? resp.getTargetNum() : -1;
        String sout = "预言家查验了玩家：" + target + "思考:" + chat;
        PrintUtils.printPlayer(emitter, prophet, sout);

        Player targetPlayer = RoleUtils.getTargetPlayer(players, target);
        String result = targetPlayer.getCamp().equals(Camp.WEREWOLF) ? "狼人" : "好人";
        String message = "【主持人 + 预言家】：预言家查验了" + target + "，查验结果为" + result;
        String acceptPlayer = "预言家";
        PrintUtils.printSystem(emitter, message);

//        List<Player> acceptPlayers = RoleUtils.getRoleplayer(players, acceptPlayer);
//        List<Integer> acceptPlayerIds = acceptPlayers.stream().map(Player::getId).toList();
        prophet.addEvent(Event.builder()
                .description(resp.getContent() + "，查验结果为" + result)
                .affectedPlayer(Collections.singletonList(prophet.getId()))
                .build());

        return ActionSkill.builder()
                .actionType(ActionType.PROPHET_CHECK)
                .prophetTargetNum(target)
                .build();
    }

    private GameChatResp parseResponse(String json) {
        try {
            return JSONObject.parseObject(json, GameChatResp.class);
        } catch (Exception e) {
            System.err.println("解析预言家响应失败: " + e.getMessage());
            return null;
        }
    }
}
